import {View, Text, ScrollView} from '@tarojs/components'
import  {useDidShow, useLoad, usePullDownRefresh, useReachBottom} from '@tarojs/taro'
import {
  Cell, CellGroup, Empty,

  Search,
  Swiper,
  Image,
  SwiperItem
} from "@antmjs/vantui";


import {useCallback, useEffect, useMemo,  useState} from "react";
import {AdsModel, ProjectModel, ZiXunModel} from "@/common/apis/model";
import Utils from "@/utils/common";
import AssetImage from "@/common/AssetImage";

import RouthPath from "@/common/RouthPath";

import {activityListApi, adsListApi, projectHotApi} from "@/common/apis/home_datasource";
import LogUtils from "@/utils/log";
import ShowUtils from "@/utils/show_utils";
import LocalData from "@/common/local_data";
import StyleUtils from "@/utils/style_utils";
import CustomNavBar from '@/components/CustomNavBar';


definePageConfig({
  navigationBarTitleText: '首页',
  enablePullDownRefresh: true,
  onReachBottomDistance: 50,
  enableShareAppMessage: true,
  navigationStyle: 'custom',
  enableShareTimeline: true,

})


export default function Home() {
  useLoad(() => {
    console.log('Page loaded.')
  })

  useDidShow(() => {
     LocalData.currentIndex = 0;
  })


  const onRefresh = useCallback(async () => {
    const data = await adsListApi();
    const data2 = await projectHotApi();
    const data3 = await activityListApi();
    LogUtils.info(data)
    if (data) {
      setAdsModel(data);
    }

    if (data2) {
      setHotProject(data2);
    }

    if (data3) {
      setZxModel(data3);
    }
    Utils.stopRefresh()
  }, []);


  const [adsModel, setAdsModel] = useState<AdsModel[]>()
  const [hotProject, setHotProject] = useState<ProjectModel[]>()
  const [zxModel, setZxModel] = useState<ZiXunModel[]>()



  useReachBottom(() => {
    console.log('reach bottom');
  });

  usePullDownRefresh(() => {
    onRefresh().then(() => {
    })
  })


  const renderTitle = useCallback((title, value?: string) => {
    return (<View
      style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}
    ><Text
      style={{color: 'black', fontSize: '16px'}}
    >{title}</Text>
      {
        value ? <Text style={{color: 'gray', fontSize: '12px'}}>{value}</Text> : null
      }
    </View>)
  }, []);

  const renderImage = useCallback((image) => {
    LogUtils.info(Utils.isNotBlank(image))
    return (Utils.isNotBlank(image) ? <Image src={ShowUtils.getImageUrl(image)} style={{width: '50px', height: '50px',marginRight:'10px'}} /> : null)
  }, []);


  const SwiperHeight = "170px"


  useEffect(() => {
    onRefresh().then(() => {
    });
  }, [onRefresh]);
  const max1Style = useMemo(() => {
    return StyleUtils.getMaxLines()
  }, []);
  return (
    <View style={{height: '100vh', backgroundColor: AssetImage.bg,minHeight: "100vh"}}>

      <CustomNavBar
        title='首页'
        showLeftIcon // 首页通常不显示返回按钮
        leftIconName={AssetImage.logo3}
      >
        <Search
          shape='round'
          background='transparent'
          placeholder='请输入搜索关键词'
          disabled
          onClick={() => {
            Utils.navigateTo({ url: RouthPath.searchProject })
          }}
        />
      </CustomNavBar>

      <View style={{padding: '10px 15px 0 15px', boxSizing: 'border-box', display: 'flex', flexDirection: 'row'}}>
        <View style={{flex: '1', height: SwiperHeight}}>
          {
            Utils.isEmpty(adsModel) ? null : <Swiper
              height={SwiperHeight}
              width='100%'
              paginationColor='#426543'
              autoPlay='3000'
              initPage={0}
              paginationVisible
            >
              {
                adsModel?.map((item) => (
                  <SwiperItem key={item.id}>
                    <Image src={ShowUtils.getImageUrl(item.image)} radius={15} fit='cover' style={{width: '100%', height: SwiperHeight}} />
                  </SwiperItem>
                ))
              }
            </Swiper>
          }
        </View>
      </View>
      <CellGroup title={renderTitle('热门项目')} inset>
        <ScrollView
          style={{
            width: '100%',
            height: '160px',
            boxSizing: 'border-box',
            padding: '10px 10px',
          }}
          scrollX
          scrollWithAnimation
        >
          <View style={{display: 'flex', flexDirection: 'row', gap: '10px', height: '100%'}}>
            {
              hotProject && !Utils.isEmpty(hotProject) ? hotProject.map((item) => (
                <View style={{
                  width: '150px',
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'center',
                  alignItems: 'center',
                }} key={item.id} onClick={() => {
                  item.note = ''
                  Utils.navigateTo({
                    url: Utils.getUrlWithObject(RouthPath.projectDetail, {
                      machineId: null,
                      projectId: item
                    }),
                  })
                }}
                >
                  <Image src={ShowUtils.getImageUrl(item.image)} style={{width: '150px', flex: 1}} fit='cover' radius={10} />
                  <View style={{height: '40px'}}>
                    <Text style={{display: 'block', textAlign: 'center'}}>{item.name}</Text>
                  </View>
                </View>
              )) : null
            }
          </View>
        </ScrollView>
      </CellGroup>

      <CellGroup title={renderTitle('热门活动')} inset>
        {
          Utils.isEmpty(zxModel) ? <Empty description='暂无数据' /> : zxModel.map((item, index) => (
            <Cell renderIcon={renderImage(item.image)}
              renderLabel={<Text style={max1Style}>{ShowUtils.getFirstParagraphContentRegex(item.content)}</Text>}
              key={`swiper#demo1${index}`} renderTitle={<Text>{item.title}</Text>} isLink
              onClick={() => {
                    Utils.navigateTo({
                      url: Utils.getUrlWithObject(RouthPath.webDetail, {
                        title: item.title,
                        content: item.content
                      })
                    })
                  }}
            />
          ))
        }
      </CellGroup>
    </View>
  )
}



